<template>
  <div style="padding: 30px;">
    <!-- 文件上传 -->
    <upload-box @uploadSuccess="handleUploadSuccess"></upload-box>

    <!-- 文件列表 -->
    <v-row>
      <v-col v-for="file in files" :key="file.fileName" cols="12" sm="6" md="3" lg="2" xl="1.5">
        <v-card>
          <!-- 图片文件预览 -->
          <v-img v-if="isImage(file.fileName)" :src="file.url" :alt="file.fileName" class="file-thumbnail"
            aspect-ratio="1">
            <template v-slot:placeholder>
              <v-progress-circular indeterminate color="primary" size="40" />
            </template>
          </v-img>

          <!-- 非图片文件图标 -->
          <v-icon v-else class="file-icon" :color="getIconColor(file.fileName)" size="48">
            {{ getFileIcon(file.fileName) }}
          </v-icon>

          <v-card-title class="text-center">{{ file.fileName }}</v-card-title>
          <v-card-subtitle>{{ file.formattedLastModified }}</v-card-subtitle>

          <!-- 文件大小展示 -->
          <v-card-text>
            <span>{{ formatFileSize(file.size) }}</span>
          </v-card-text>

          <!-- 文件 URL 展示 -->
          <v-card-text>
            <span style="word-break: break-all;">{{ file.url }}</span>
          </v-card-text>

          <!-- 复制链接和删除按钮 -->
          <v-card-actions>
            <v-btn color="primary" @click="copyToClipboard(file.url)" size="small">
              复制链接
            </v-btn>
            <v-btn color="red" @click="confirmDelete(file.fileName)" size="small">
              删除
            </v-btn>
          </v-card-actions>
        </v-card>
      </v-col>
    </v-row>

    <!-- Snackbar 提示消息 -->
    <v-snackbar v-model="snackbar.visible" :timeout="snackbar.timeout">
      {{ snackbar.message }}
      <template #actions>
        <v-btn color="white" text @click="snackbar.visible = false">关闭</v-btn>
      </template>
    </v-snackbar>

    <v-dialog v-model="deleteDialog" max-width="400px">
      <v-card>
        <v-card-title class="headline">确认删除</v-card-title>
        <v-card-text>确定要删除文件 "{{ fileToDelete }}" 吗？</v-card-text>
        <v-card-actions>
          <v-btn color="grey" @click="deleteDialog = false">取消</v-btn>
          <v-btn color="red" @click="deleteFile">删除</v-btn>
        </v-card-actions>
      </v-card>
    </v-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { useRoute } from 'vue-router';
import api from '@/utils/api';
import useClipboard from "vue-clipboard3";
import UploadBox from '@/components/UploadBox.vue';
const route = useRoute();
// 文件列表
const files = ref([]);
const deleteDialog = ref(false); // 删除对话框的显示状态
const fileToDelete = ref(""); // 当前待删除的文件名
let folderRoot = route.query.target;  //这里根据地址栏参数使用不同的文件夹
if (folderRoot == undefined) {
  folderRoot = 'uploads';
}

const url = window.location.href;
// 使用 URL 对象来解析 URL
const parsedUrl = new URL(url);
// 获取协议和主机（包括端口）
const webRoot = parsedUrl.origin;
// Snackbar 配置
const snackbar = ref({
  visible: false, // 是否显示
  message: '',    // 提示消息
  timeout: 3000,  // 自动消失时间 (ms)
});
api.setRootFolder(folderRoot);
// 获取文件列表
const fetchFiles = async () => {
  const res = await api.fetchFiles();
  files.value.push(...res.data.map((file) => ({
    ...file,
    url: `${webRoot}/assets/${folderRoot}/${file.fileName}`
  })));
};
const handleUploadSuccess = () => {
  files.value = [];
  fetchFiles();
}
// 组件挂载后请求文件列表
onMounted(() => {
  fetchFiles();
});

// 判断文件是否为图片
const isImage = (fileName) => {
  return /\.(jpg|jpeg|png|gif|bmp|webp)$/i.test(fileName);
}

// 根据文件扩展名获取对应的图标
const getFileIcon = (fileName) => {
  const fileExt = fileName.split('.').pop().toLowerCase();
  const iconMap = {
    pdf: 'mdi-home',
    txt: 'mdi-file-document',
    doc: 'mdi-file-word',
    docx: 'mdi-file-word',
    zip: 'mdi-file-archive',
    mp3: 'mdi-file-music',
    default: 'mdi-file',
  };
  return iconMap[fileExt] || iconMap.default; // 返回对应的图标
}

// 根据文件类型返回图标颜色
const getIconColor = (fileName) => {
  const fileExt = fileName.split('.').pop().toLowerCase();
  const colorMap = {
    pdf: 'red',
    txt: 'blue',
    doc: 'green',
    docx: 'green',
    zip: 'orange',
    mp3: 'purple',
  };
  return colorMap[fileExt] || 'grey'; // 返回对应的颜色
}

// 复制文本到剪贴板
const copyToClipboard = async (text) => {
  try {
    const { toClipboard } = useClipboard();
    await toClipboard(text);
    showSnackbar('已复制');
  } catch (error) {
    showSnackbar('复制失败，请手动复制！');
  }
}

// 格式化文件大小
const formatFileSize = (bytes) => {
  if (bytes < 1024) return `${bytes} B`;
  else if (bytes < 1048576) return `${(bytes / 1024).toFixed(2)} KB`;
  else if (bytes < 1073741824) return `${(bytes / 1048576).toFixed(2)} MB`;
  else return `${(bytes / 1073741824).toFixed(2)} GB`;
}

const confirmDelete = (fileName) => {
  fileToDelete.value = fileName;
  deleteDialog.value = true;
};

const deleteFile = async () => {
  const fileName = fileToDelete.value;
  deleteDialog.value = false;
  const msg = await api.deleteFile(fileName);
  showSnackbar(msg);
  if (msg.indexOf('成功') > -1) {
    files.value = files.value.filter(
      (file) => file.fileName !== fileName
    );
  }

};

// 显示 Snackbar
const showSnackbar = (message) => {
  snackbar.value.message = message;
  snackbar.value.visible = true;
};

</script>

<style scoped>
.file-thumbnail {
  width: 100%;
  height: auto;
}

.file-icon {
  display: block;
  margin: 0 auto;
  padding: 10px;
  text-align: center;
}

.v-card {
  max-width: 250px;
  /* 缩小卡片宽度 */
  margin: auto;
}

.v-btn {
  font-size: 0.875rem;
  /* 缩小按钮字体 */
}
</style>